import { __private, _decorator, Component, instantiate, Node, Prefab } from 'cc';
import { GameUnit } from './Unit/GameUnit';
import { ResMgr } from '../../ISUtility/Script/ResMgr';
const { ccclass, property } = _decorator;

@ccclass('UnitMgr')
export class UnitMgr extends Component {

    private static _inst: UnitMgr;
    public static get inst(): UnitMgr {
        return UnitMgr._inst;
    }

    protected onLoad(): void {
        UnitMgr._inst = this;
    }



    public Create<T extends GameUnit>(paths : string,type: __private._types_globals__Constructor<T>,callBakc : (unit : T)=> void) {
        ResMgr.inst.load(paths, Prefab, null, (err, prefab) => {
            if (err) {
                console.log(err);
                return;
            }
            let unit = instantiate(prefab);
            this.node.addChild(unit);
            callBakc(unit.getComponent(type));
        });
    }

    public FindUnit<T extends GameUnit>(type: __private._types_globals__Constructor<T>) : T {
        for(let i=0;i < this.node.children.length;++i) {
            let unit = this.node.children[i].getComponent(type);
            if(unit)
                return unit;
        }
        return null;
    }
}


